﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using System.Windows.Media.Imaging;

using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Kinect;
using Microsoft.Kinect.Toolkit;
using Microsoft.Kinect.Toolkit.Controls;
using System.IO;
using System.Windows.Threading ;
using System.Globalization;





namespace KinectProject
{



    /// <summary>
    /// Interaction logic for Page1.xaml
    /// </summary>
    public partial class DisplayPage : Window
    {

        Pages.vas vasPage;
        dbController db;
        ImageBrush targetBrush, targetHitBrush;
        private SolidColorBrush clipedBrush;

        SkeletonPoint targetSkelPoint;
        DispatcherTimer dispatcherTimer;
        Storyboard s;
        private System.Media.SoundPlayer player;
        
        //used for flex 
        double t, a, targetY, targetZ, theta, sin, cos;
        Vector3D vSC1, vHC, vSL, vWL, vOrgin, vFinish,vTarget,vArm;

        private bool blackBackground = true,
                     first           = true,
                     placeTarget     = false, 
                     trialStarted    = false, 
                     startMovement   = false;

        double timerMilisecond = 0;
        int vasIndex = 0;

    
        //  Skeleton Window
        //------------------------------------------------------
        private readonly KinectSensorChooser sensorChooser;
        private const float RenderWidth = 640.0f;
        private const float RenderHeight = 480.0f;
        private const double JointThickness = 3;
        private const double BodyCenterThickness = 10;
        private const double ClipBoundsThickness = 10;
        private readonly Brush centerPointBrush = Brushes.Blue;
        private readonly Brush trackedJointBrush = new SolidColorBrush(Color.FromArgb(255, 68, 192, 68));
        private readonly Pen trackedBonePen = new Pen(Brushes.Green, 6);
        private readonly Brush inferredJointBrush = Brushes.Yellow;
        private readonly Pen inferredBonePen = new Pen(Brushes.Gray, 1);
        private KinectSensor sensor;
        private DrawingGroup drawingGroup;
        private DrawingImage imageSource;




   
        public DisplayPage()
        {
            this.InitializeComponent();
            this.sensorChooser = new KinectSensorChooser();
            scrollViewer.ScrollChanged += (o, e) => this.UpdateScrollState();
               
        
        }
        /// <summary>
        /// Execute startup tasks
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {

           vasPage = new Pages.vas();

           db = new dbController();

            // initialize the sensor chooser and UI
            this.sensorChooser.KinectChanged += SensorChooserOnKinectChanged;
            this.sensorChooserUi.KinectSensorChooser = this.sensorChooser;
            this.sensorChooser.Start();

            //// Bind the sensor chooser's current sensor to the KinectRegion
            var regionSensorBinding = new Binding("Kinect") { Source = this.sensorChooser };
            BindingOperations.SetBinding(this.kinectRegion, KinectRegion.KinectSensorProperty, regionSensorBinding);


            // Bind listner to scrollviwer scroll position change, and check scroll viewer position
            this.UpdateScrollState();

            //timer
            dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(1));

 

            // Create the drawing group we'll use for drawing
            this.drawingGroup = new DrawingGroup();

            // Create an image source that we can use in our image control
            this.imageSource = new DrawingImage(this.drawingGroup);

            // Display the drawing using our image control
            this.Image.Source = this.imageSource;

            // Look through all sensors and start the first connected one.
            // This requires that a Kinect is connected at the time of app startup.
            // To make your app robust against plug/unplug, 
            // it is recommended to use KinectSensorChooser provided in Microsoft.Kinect.Toolkit (See components in Toolkit Browser).
            foreach (var potentialSensor in KinectSensor.KinectSensors)
            {
                if (potentialSensor.Status == KinectStatus.Connected)
                {
                    this.sensor = potentialSensor;
                    break;
                }
            }

            if (null != this.sensor)
            {
                // Turn on the skeleton stream to receive skeleton frames
                this.sensor.SkeletonStream.Enable();

                // Add an event handler to be called whenever there is new camera data
                sensor.AllFramesReady += new EventHandler<AllFramesReadyEventArgs>(sensor_AllFramesReady);
                sensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
                sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
 
                // Start the sensor!
                try
                {
                    this.sensor.Start();
                }
                catch (IOException)
                {
                    this.sensor = null;
                }
            }

            if (null == this.sensor)
            {
                //this.statusBarText.Text = Properties.Resources.NoKinectReady;
            }
        }

        /// <summary>
        /// Event handler for Kinect sensor's SkeletonFrameReady event
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void sensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
        {
            //if (!placeTarget)
            //{
                Skeleton[] skeletons = new Skeleton[0];

                using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
                {
                    if (skeletonFrame != null)
                    {
                        skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
                        skeletonFrame.CopySkeletonDataTo(skeletons);
                    }
                }

                using (DrawingContext dc = this.drawingGroup.Open())
                {
                    // Draw a transparent background to set the render size
                    if (blackBackground)
                    {
                        dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, RenderWidth, RenderHeight));
                    }
                    else
                    {
                        dc.DrawRectangle(Brushes.White, null, new Rect(0.0, 0.0, RenderWidth, RenderHeight));

                    }
                    if (skeletons.Length != 0)
                    {
                        foreach (Skeleton skel in skeletons)
                        {

                            RenderClippedEdges(skel, dc);

                            if (skel.TrackingState == SkeletonTrackingState.Tracked)
                            {
                                //check for all joints...
                                /*
                                foreach (Joint joint in skel.Joints)
                                {
                                    // If we can't find either of these joints, exit
                                    if (joint.TrackingState == JointTrackingState.NotTracked )
                                    {
                                        return;
                                    }
                                }*/

                                this.DrawBonesAndJoints(skel, dc);

                                if (placeTarget)
                                {
                                    this.DrawTarget(skel, dc, e);
                                }
                                if (trialStarted)
                                {

                                    if (startMovement)
                                    {
                                        checkedForHitTarget(skel);
                                    }
                                    else
                                    {
                                        checkForNintyDegree(skel);
                                    }
                                    //wait for start position


                                }
                            }
                            else if (skel.TrackingState == SkeletonTrackingState.PositionOnly)
                            {
                                dc.DrawEllipse(this.centerPointBrush, null, this.SkeletonPointToScreen(skel.Position),
                                BodyCenterThickness,
                                BodyCenterThickness);
                            }
                        }
                    }

                    // prevent drawing outside of our render area
                    this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, RenderWidth, RenderHeight));
                }
            //}//if(!placedTarget)
        }

        private void checkForNintyDegree(Skeleton skel)
        {
            Point rightHand = SkeletonPointToScreen(skel.Joints[JointType.HandLeft].Position),
                  leftHand = SkeletonPointToScreen(skel.Joints[JointType.HandRight].Position),
                  shoulderCenter = SkeletonPointToScreen(skel.Joints[JointType.ShoulderCenter].Position);

            //(points ar measured from top left
            if(rightHand.Y <= shoulderCenter.Y+50 && leftHand.Y <= shoulderCenter.Y+50 ){
                if (timerMilisecond > 3)
                {
                    startMovement = true;
                    dispatcherTimer.Stop();
                    timerMilisecond = 0;

                    //fade out messageGrid
                    messageGrid.Visibility = Visibility.Hidden;

                    //or use a storyboard

                    dispatcherTimer.Start();
                }

                messageLabel.Content = 4.0 - timerMilisecond;                                             
            }
            else
            {
                messageLabel.Content = "Please hold your arms at a 90 degree angle";
                timerMilisecond = 0;
            }

    
        }
        private void checkedForHitTarget(Skeleton skeleton)
        {
            if (Math.Round(100 * skeleton.Joints[JointType.WristLeft].Position.Y) == 
                Math.Round(100 * targetSkelPoint.Y))
            {
                dispatcherTimer.Stop();
                log.time = timerMilisecond/100;
                //target hit!
                trialStarted = false;
                startMovement = false;
                
                targetBrush = new ImageBrush();
                targetBrush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/boom.png", UriKind.Absolute));

                player = new System.Media.SoundPlayer(Application.GetResourceStream(new Uri("pack://application:,,,/audio/canopus.wav", UriKind.Absolute)).Stream);
                player.Play();

                nextVas(skeleton, null);
            }

        }
        private void calculateFlex(Skeleton skeleton, AllFramesReadyEventArgs e)
        {


            vSC1 = new Vector3D(skeleton.Joints[JointType.ShoulderCenter].Position.X,
                         skeleton.Joints[JointType.ShoulderCenter].Position.Y,
                         skeleton.Joints[JointType.ShoulderCenter].Position.Z);
            vHC = new Vector3D(skeleton.Joints[JointType.HipCenter].Position.X,
                    skeleton.Joints[JointType.HipCenter].Position.Y,
                    skeleton.Joints[JointType.HipCenter].Position.Z);
            vSL = new Vector3D(skeleton.Joints[JointType.ShoulderLeft].Position.X,
                        skeleton.Joints[JointType.ShoulderLeft].Position.Y,
                        skeleton.Joints[JointType.ShoulderLeft].Position.Z);
            vWL = new Vector3D(skeleton.Joints[JointType.WristLeft].Position.X,
                        skeleton.Joints[JointType.WristLeft].Position.Y,
                        skeleton.Joints[JointType.WristLeft].Position.Z);
            if(first){


                //calculate torso start position and arm (used for length only), 
                first = false;
                vOrgin = vHC - vSC1;
                vArm = vSL - vWL;

                //set up target image
                targetBrush = new ImageBrush();
                targetBrush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/BlueBalloon.png", UriKind.Absolute));
            
                //Make skeleton point 
                targetSkelPoint = new SkeletonPoint();
            }

            //get length of arm and torso
            a = vArm.Length;
            t = vOrgin.Length;

            //convert flexion to radians
            theta = Convert.ToDouble(log.flexion) * (Math.PI/ 180 );

            //get Abs value (deal with +/- later)
            cos = Math.Abs(Math.Cos(theta));
            sin = Math.Abs(Math.Sin(theta));

            targetSkelPoint.X = (float)vHC.X;
            targetSkelPoint.Y = (float)((t * cos) - (a * sin));
            targetSkelPoint.Z = (float)(vHC.Z- ((t * sin) + (a * cos)));


            //get current flexion 
            vFinish = vHC - vSC1;
            Double angleBetween;
            angleBetween = Vector3D.AngleBetween(vOrgin, vFinish);
            flex.Content = Math.Round(angleBetween);
            //note: orgin is calculated only if first == true
            //if subject has moved, orgin needs to be recalculated


    
    
        }

        private void DrawTarget(Skeleton skeleton, DrawingContext drawingContext, AllFramesReadyEventArgs e)
        {
   
            calculateFlex(skeleton, e);
            targetFlex.Content = log.flexion;

            //draw hip
            // drawingContext.DrawEllipse(new SolidColorBrush(Colors.Red), null, this.SkeletonPointToScreen(skeleton.Joints[JointType.HipCenter].Position), 20, 20);

            //draw target
            Point s = this.SkeletonPointToScreen(targetSkelPoint);
            drawingContext.DrawEllipse(targetBrush, null, s,  20, 30);

            targetDisplayX.Content = s.X;
            targetDisplayY.Content = s.Y;
        
        }
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {

            timerMilisecond += 1;
            time.Content = timerMilisecond / 100;
        }






        /// <summary>
        /// Draws indicators to show which edges are clipping skeleton data
        /// </summary>
        /// <param name="skeleton">skeleton to draw clipping information for</param>
        /// <param name="drawingContext">drawing context to draw to</param>
        private static void RenderClippedEdges(Skeleton skeleton, DrawingContext drawingContext)
        {
            SolidColorBrush brush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FF246C1D"));

            if (skeleton.ClippedEdges.HasFlag(FrameEdges.Bottom))
            {
                drawingContext.DrawRectangle(
                    brush,
                    null,
                    new Rect(0, RenderHeight - ClipBoundsThickness, RenderWidth, ClipBoundsThickness));
            }

            if (skeleton.ClippedEdges.HasFlag(FrameEdges.Top))
            {
                drawingContext.DrawRectangle(
                    brush,
                    null,
                    new Rect(0, 0, RenderWidth, ClipBoundsThickness));
            }

            if (skeleton.ClippedEdges.HasFlag(FrameEdges.Left))
            {
                drawingContext.DrawRectangle(
                    brush,
                    null,
                    new Rect(0, 0, ClipBoundsThickness, RenderHeight));
            }

            if (skeleton.ClippedEdges.HasFlag(FrameEdges.Right))
            {
                drawingContext.DrawRectangle(
                    brush,
                    null,
                    new Rect(RenderWidth - ClipBoundsThickness, 0, ClipBoundsThickness, RenderHeight));
            }
        }
     

        /// <summary>
        /// Draws a skeleton's bones and joints
        /// </summary>
        /// <param name="skeleton">skeleton to draw</param>
        /// <param name="drawingContext">drawing context to draw to</param>
        private void DrawBonesAndJoints(Skeleton skeleton, DrawingContext drawingContext)
        {   



            // Render Torso
            this.DrawBone(skeleton, drawingContext, JointType.Head, JointType.ShoulderCenter);
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.ShoulderLeft);
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.ShoulderRight);
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.Spine);
            this.DrawBone(skeleton, drawingContext, JointType.Spine, JointType.HipCenter);
            this.DrawBone(skeleton, drawingContext, JointType.HipCenter, JointType.HipLeft);
            this.DrawBone(skeleton, drawingContext, JointType.HipCenter, JointType.HipRight);

            // Left Arm
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderLeft, JointType.ElbowLeft);
            this.DrawBone(skeleton, drawingContext, JointType.ElbowLeft, JointType.WristLeft);
            this.DrawBone(skeleton, drawingContext, JointType.WristLeft, JointType.HandLeft);

            // Right Arm
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderRight, JointType.ElbowRight);
            this.DrawBone(skeleton, drawingContext, JointType.ElbowRight, JointType.WristRight);
            this.DrawBone(skeleton, drawingContext, JointType.WristRight, JointType.HandRight);

            // Left Leg
            this.DrawBone(skeleton, drawingContext, JointType.HipLeft, JointType.KneeLeft);
            this.DrawBone(skeleton, drawingContext, JointType.KneeLeft, JointType.AnkleLeft);
            this.DrawBone(skeleton, drawingContext, JointType.AnkleLeft, JointType.FootLeft);

            // Right Leg
            this.DrawBone(skeleton, drawingContext, JointType.HipRight, JointType.KneeRight);
            this.DrawBone(skeleton, drawingContext, JointType.KneeRight, JointType.AnkleRight);
            this.DrawBone(skeleton, drawingContext, JointType.AnkleRight, JointType.FootRight);

            // Render Joints
            foreach (Joint joint in skeleton.Joints)
            {
                Brush drawBrush = null;

                if (joint.TrackingState == JointTrackingState.Tracked)
                {
                    drawBrush = this.trackedJointBrush;
                }
                else if (joint.TrackingState == JointTrackingState.Inferred)
                {
                    drawBrush = this.inferredJointBrush;
                }

                if (drawBrush != null)
                {
                    drawingContext.DrawEllipse(drawBrush, null, this.SkeletonPointToScreen(joint.Position), JointThickness, JointThickness);
                
                }



            }
        }

        /// <summary>
        /// Maps a SkeletonPoint to lie within our render space and converts to Point
        /// </summary>
        /// <param name="skelpoint">point to map</param>
        /// <returns>mapped point</returns>
        private Point SkeletonPointToScreen(SkeletonPoint skelpoint)
        {
            // Convert point to depth space.  
            // We are not using depth directly, but we do want the points in our 640x480 output resolution.
            DepthImagePoint depthPoint = this.sensor.CoordinateMapper.MapSkeletonPointToDepthPoint(skelpoint, DepthImageFormat.Resolution640x480Fps30);
            return new Point(depthPoint.X, depthPoint.Y);
        }

        /// <summary>
        /// Draws a bone line between two joints
        /// </summary>
        /// <param name="skeleton">skeleton to draw bones from</param>
        /// <param name="drawingContext">drawing context to draw to</param>
        /// <param name="jointType0">joint to start drawing from</param>
        /// <param name="jointType1">joint to end drawing at</param>
        private void DrawBone(Skeleton skeleton, DrawingContext drawingContext, JointType jointType0, JointType jointType1)
        {
            Joint joint0 = skeleton.Joints[jointType0];
            Joint joint1 = skeleton.Joints[jointType1];

            // If we can't find either of these joints, exit
            if (joint0.TrackingState == JointTrackingState.NotTracked ||
                joint1.TrackingState == JointTrackingState.NotTracked)
            {
                return;
            }

            // Don't draw if both points are inferred
            if (joint0.TrackingState == JointTrackingState.Inferred &&
                joint1.TrackingState == JointTrackingState.Inferred)
            {
                return;
            }

            // We assume all drawn bones are inferred unless BOTH joints are tracked
            Pen drawPen = this.inferredBonePen;
            if (joint0.TrackingState == JointTrackingState.Tracked && joint1.TrackingState == JointTrackingState.Tracked)
            {
                drawPen = this.trackedBonePen;
            }

            drawingContext.DrawLine(drawPen, this.SkeletonPointToScreen(joint0.Position), this.SkeletonPointToScreen(joint1.Position));



        }

        /// <summary>
        /// Called when the KinectSensorChooser gets a new sensor
        /// </summary>
        /// <param name="sender">sender of the event</param>
        /// <param name="args">event arguments</param>
        private static void SensorChooserOnKinectChanged(object sender, KinectChangedEventArgs args)
        {
            if (args.OldSensor != null)
            {
                try
                {
                    args.OldSensor.DepthStream.Range = DepthRange.Default;
                    args.OldSensor.SkeletonStream.EnableTrackingInNearRange = false;
                    args.OldSensor.DepthStream.Disable();
                    args.OldSensor.SkeletonStream.Disable();
                }
                catch (InvalidOperationException)
                {
                    // KinectSensor might enter an invalid state while enabling/disabling streams or stream features.
                    // E.g.: sensor might be abruptly unplugged.
                }
            }

            if (args.NewSensor != null)
            {
                try
                {
                    args.NewSensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
                    args.NewSensor.SkeletonStream.Enable();

                    try
                    {
                        args.NewSensor.DepthStream.Range = DepthRange.Near;
                        args.NewSensor.SkeletonStream.EnableTrackingInNearRange = true;
                    }
                    catch (InvalidOperationException)
                    {
                        // Non Kinect for Windows devices do not support Near mode, so reset back to default mode.
                        args.NewSensor.DepthStream.Range = DepthRange.Default;
                        args.NewSensor.SkeletonStream.EnableTrackingInNearRange = false;
                    }
                }
                catch (InvalidOperationException)
                {
                    // KinectSensor might enter an invalid state while enabling/disabling streams or stream features.
                    // E.g.: sensor might be abruptly unplugged.
                }
            }
        }


   

        /// <summary>
        /// Change button state depending on scroll viewer position
        /// </summary>
        private void UpdateScrollState()
        {
            //get value for vas question
            offset.Content = (int)(100-((scrollViewer.HorizontalOffset / scrollViewer.ActualWidth) * 100));

            //this.PageLeftEnabled = scrollViewer.HorizontalOffset > ScrollErrorMargin;
            //this.PageRightEnabled = scrollViewer.HorizontalOffset < scrollViewer.ScrollableWidth - ScrollErrorMargin;
        }



        private void nextVas(object sender, RoutedEventArgs e)
        {
            int value = (int)((scrollViewer.HorizontalOffset / scrollViewer.ActualWidth)  * 100);
            double offset  = scrollViewer.ActualWidth / 2;
            switch (vasIndex)
            {

                case 0:
                    vasFrame.Navigate(vasPage);
                    vasFrame.Visibility = Visibility.Visible;
                    lessHoverButton.Visibility = Visibility.Visible;
                    moreHoverButton.Visibility = Visibility.Visible;
                    sliderGrid.Visibility = Visibility.Visible;

                    //start showVAS animation
                    s = (Storyboard)TryFindResource("showVAS");
                    s.Begin();	// Start animation


                    scrollViewer.ScrollToHorizontalOffset(offset);
                    blackBackground = true;

                    //calculate target
                    placeTarget = true;

                    // vas 1
                    //-------------------------------------------
                    //vasPage.vasLabel1.Content = "No Pain";
                    //vasPage.vasLabel2.Content = "Worst Possible Pain";
                    vasPage.vasTextBox.Text = "How much pain do you expecet when reaching for this target?";
                    vasIndex++;
                   break;
                case 1:
                    // vas 2
                    //-------------------------------------------
                    log.pain = value; //collect 
                    scrollViewer.ScrollToHorizontalOffset(offset);
                    vasPage.vasTextBox.Text = "How concerned are you about harming or injuring your back when reaching for this target?";
                    vasIndex++;
                    break;
                case 2:
                    // vas 3
                    //-------------------------------------------
                
                    log.harm = value;
                    scrollViewer.ScrollToHorizontalOffset(offset);
                    vasPage.vasTextBox.Text = "How anxious are you feeling right now?";
                    vasIndex++;
                    break;
                case 3:
                    //  begin trial
                    //---------------------------------------------
                    
                    log.anxiety = value;
                    scrollViewer.ScrollToHorizontalOffset(offset);


                    vasFrame.Visibility       = Visibility.Hidden;
                    sliderGrid.Visibility     = Visibility.Hidden;
                    navGrid.Visibility        = Visibility.Hidden;
                    
                    s = (Storyboard)TryFindResource("closeVas");
                    s.Begin();	// Start animation
                    
                    kinectRegion.Visibility   = Visibility.Hidden;
                    messageGrid.Visibility    = Visibility.Visible;

                    trialStarted = true;
                    dispatcherTimer.Start();

                    vasIndex++;
                    break;
                case 4:
                    //  post vas
                    //----------------------------------------

                    vasFrame.Visibility = Visibility.Visible;
                    navGrid.Visibility = Visibility.Visible;
                    sliderGrid.Visibility = Visibility.Visible;
                    kinectRegion.Visibility = Visibility.Visible;
                    s = (Storyboard)TryFindResource("showVAS");
                    s.Begin();	// Start animation

                    vasPage.vasTextBox.Text = "How much pain did you experience when reaching for this target?";
                    vasIndex++;
                    break;
                case 5:

                    // go back to start
                    //-----------------------------------
                    log.epain = value;

                    vasFrame.Visibility          = Visibility.Hidden;
                    lessHoverButton.Visibility   = Visibility.Hidden;
                    moreHoverButton.Visibility   = Visibility.Hidden;
                    sliderGrid.Visibility        = Visibility.Hidden;

                    s = (Storyboard)TryFindResource("closeVas");
                    s.Begin();	

                    //blackBackground        = false;
                    vasPage.index          = 1;
                    placeTarget            = false;
                    first                  = true;

                    db.saveResults();
                    if (!db.getNextValues())
                    {
                        //db.close();
                        this.Close();
                    }
                    vasIndex = 0;

                    break;
            }



            
            }


        private const double ScrollErrorMargin = 0.001;
        private const int PixelScrollByAmount = 10;

        /*

        public static readonly DependencyProperty PageLeftEnabledProperty = DependencyProperty.Register(
        "PageLeftEnabled", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
        public static readonly DependencyProperty PageRightEnabledProperty = DependencyProperty.Register(
            "PageRightEnabled", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));


        /// <summary>
        /// CLR Property Wrappers for PageLeftEnabledProperty
        /// </summary>
        public bool PageLeftEnabled
        {
            get
            {
                return (bool)GetValue(PageLeftEnabledProperty);
            }

            set
            {
                this.SetValue(PageLeftEnabledProperty, value);
            }
        }

        /// <summary>
        /// CLR Property Wrappers for PageRightEnabledProperty
        /// </summary>
        public bool PageRightEnabled
        {
            get
            {
                return (bool)GetValue(PageRightEnabledProperty);
            }

            set
            {
                this.SetValue(PageRightEnabledProperty, value);
            }
        }

        */

        /// <summary>
        /// Handle paging right (next button).
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void PageRightButtonClick(object sender, RoutedEventArgs e)
        {
            scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + PixelScrollByAmount);
        }

        /// <summary>
        /// Handle paging left (previous button).
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void PageLeftButtonClick(object sender, RoutedEventArgs e)
        {
            scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset - PixelScrollByAmount);
        }



        private void showVasCompleted(object sender, EventArgs e)
        {
            vasPage.Visibility = Visibility.Visible;

        }

        private void closeVasCompleted(object sender, EventArgs e)
        {
            vasPage.Visibility = Visibility.Hidden;
        }

        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {
            if (null != this.sensor)
            {
                this.sensor.Stop();
            }
            this.sensorChooser.Stop();
            db.close();
        }
       




    }


}
